#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <signal.h>

#include "Constant.h"
#include "ManageRoute.h"
#include "NeighborDiscover.h"
#include "Recv.h"
#include "Beacon.h"

void sigpipe(int signo)
{
	printf("sigpipe\n");
}

int main()
{
	struct sigaction sa;
	sa.sa_handler = sigpipe;
	sigaction(SIGPIPE, &sa, 0);
	constant_init();
	printf("HOSTIP=%s,BROADCASTIP=%s,HOSTID=%d\n", HOSTIP, BROADCASTIP, HOSTID);

	ManageRoute_init();
	neighborDiscoverInit();
	recv_init();
	beacon_init();

	pthread_t id;
	pthread_attr_t attr;
	pthread_attr_init(&attr);
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

	if(pthread_create(&id, &attr, recv_departure, NULL) != 0)
	{
		//perror("recv_departure start error");
		printf("recv start error!%s\n", strerror(errno));
		//beep(2000,2000);
		abort();
		exit(1);
	}

	if(pthread_create(&id, &attr, beacon, NULL) != 0)
	{
		//perror("beacon start error");
		printf("beacon start error!%s\n", strerror(errno));
		//beep(2000,2000);
		abort();
		exit(1);
	}

	if(pthread_create(&id, &attr, calculateOverhead, NULL) != 0)
	{
		//perror("calculateOverhead start error");
		printf("calculateOverhead start error!%s\n", strerror(errno));
		//beep(2000,2000);
		abort();
		exit(1);
	}

	if(pthread_create(&id, &attr, neighborDiscover, NULL) != 0 )
	{
		//perror("broadcastRoute start error");
		printf("neighborDiscover start error!%s\n", strerror(errno));
		//beep(2000,2000);
		abort();
		exit(1);
	}

	pthread_attr_destroy(&attr);

	printf("--------------------Static Router has started successfully-------------------\n");
	while(1)
		sleep(1000);
}
